package com.atguigu.eduservice.listener;


import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.atguigu.eduservice.entity.EduSubject;
import com.atguigu.eduservice.entity.vo.ExcelSubjectData;
import com.atguigu.eduservice.service.EduSubjectService;
import com.atguigu.servicebase.handler.GuliException;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

/**
 * @author gjl
 * @create 2021-04-06 9:23
 */
public class SubjectExcelListener extends AnalysisEventListener<ExcelSubjectData> {
    private EduSubjectService subjectService;

    public SubjectExcelListener() {
    }

    public SubjectExcelListener(EduSubjectService subjectService) {
        this.subjectService = subjectService;
    }

    @Override
    public void invoke(ExcelSubjectData excelSubjectData, AnalysisContext analysisContext) {
        //验空
        if(excelSubjectData==null){
            throw new GuliException(20001,"导入课程分类信息失败");
        }
        //读取一级分类数据
        String oneSubjectName = excelSubjectData.getOneSubjectName();
        //判断一级分类是否重复 (一级名称)
        EduSubject existOneSubject = this.existOneSubject(subjectService, oneSubjectName);
        if(existOneSubject==null){
            //如果数据库没有插入数据库
            existOneSubject = new EduSubject();
            existOneSubject.setParentId("0");
            existOneSubject.setTitle(oneSubjectName);
            subjectService.save(existOneSubject);
        }

        String pid = existOneSubject.getId();
        //读取二级分类数据
        String twoSubjectName = excelSubjectData.getTwoSubjectName();
        //判断二级是否重复(二级名称、一级ID)
        EduSubject existTwoSubject = this.existTwoSubject(subjectService, twoSubjectName, pid);
        if(existTwoSubject==null){
            //如果没有插入数据库
            existTwoSubject = new EduSubject();
            existTwoSubject.setParentId(pid);
            existTwoSubject.setTitle(twoSubjectName);
            subjectService.save(existTwoSubject);
        }

    }
    //判断一级分类是否重复
    private EduSubject existOneSubject(EduSubjectService subjectService,
                                       String oneSubjectName){
        QueryWrapper<EduSubject> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("parent_id","0");
        queryWrapper.eq("title",oneSubjectName);
        EduSubject oneSubject = subjectService.getOne(queryWrapper);
        return  oneSubject;
    }

    //判断二级分类是否重复
    private EduSubject existTwoSubject(EduSubjectService subjectService,
                                       String twoSubjectName,
                                       String pid){
        QueryWrapper<EduSubject> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("parent_id",pid);
        queryWrapper.eq("title",twoSubjectName);
        EduSubject twoSubject = subjectService.getOne(queryWrapper);
        return  twoSubject;
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {

    }
}
